package com.flycent.hqhs.ui;

import java.lang.ref.WeakReference;
import java.util.List;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flycent.hqhs.App;
import com.flycent.hqhs.R;
import com.flycent.hqhs.bean.MyConsigneeAddress;
import com.flycent.hqhs.bean.PageEntity;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.ui.view.AbsViewHolderAdapter;
import com.flycent.hqhs.ui.view.DoubleButtonDialog;
import com.flycent.hqhs.ui.view.RefreshViewItemClickWrapper;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy.OnLoadDataActionListener;
import com.flycent.hqhs.ui.view.SimpleTitleBar;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

/**
 * 地址管理
 * @author fbl
 */
public class AddressManagerActivity extends BackableTitleBarActivity implements 
OnLoadDataActionListener,OnItemClickListener,OnItemLongClickListener{
	@ViewInject(id=R.id.address_empty_relat) RelativeLayout mEmptyRelat;

	private MyAddressAdapter mAdapter;

	PullToRefreshListView mRefreshListView;
	RefreshViewLoadMoreProxy mLoadMoreProxy;
	private List<MyConsigneeAddress> mConsigneeAddresses;
	String orderProperty = "createDate";
	private int nowPage = 1;
	private DoubleButtonDialog mAddressDeleteDialog;
	private MyHandler mHandler = new MyHandler(this);

	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.activity_address_manager);
		FinalActivity.initInjectedView(this);

		mRefreshListView = (PullToRefreshListView) findViewById(R.id.address_manager_list);
		mRefreshListView.setEmptyView(mEmptyRelat);
		mRefreshListView.setOnItemClickListener(new RefreshViewItemClickWrapper.OnItemClickListener(this));
		mRefreshListView.getRefreshableView().setOnItemLongClickListener(
				new RefreshViewItemClickWrapper.OnItemLongClickListener(this));

		mRefreshListView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));
		mAdapter = new MyAddressAdapter(this,R.layout.item_address_manager);
		mRefreshListView.setAdapter(mAdapter);

		mLoadMoreProxy = new RefreshViewLoadMoreProxy(mRefreshListView, Mode.BOTH,0,0);
		mLoadMoreProxy.setOnLoadDataActionListener(this);
		mLoadMoreProxy.refreshing();

	}
	@Override
	protected void onTitleBarCreated(SimpleTitleBar titleBar) {
		super.onTitleBarCreated(titleBar);
		titleBar.setTitle(R.string.title_address_manager);

		titleBar.setRightButtonText(R.string.title_address_manager_right);

		titleBar.setOnRightButtonClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(AddressManagerActivity.this,NewAddressActivity.class);
				intent.putExtra("from", "AddressManagerActivity");
				intent.putExtra("inputType", "add");
				startActivity(intent);
			}


		});
	}


	public class MyAddressAdapter extends AbsViewHolderAdapter<MyConsigneeAddress>{

		public MyAddressAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, MyConsigneeAddress itemData) {

			LinearLayout mlay = getViewFromHolder(R.id.item_adress_main_lin);
			TextView mName = getViewFromHolder(R.id.address_name_text);
			TextView mTel = getViewFromHolder(R.id.address_tel_text);
			TextView mAddrss = getViewFromHolder(R.id.address_detail_text);

			if( itemData.getIsDefault()){
				mlay.setBackgroundResource(R.drawable.setting_main_loyout_is_default);
			}else {
				mlay.setBackgroundResource(R.drawable.setting_main_loyout_selector);
			}

			mName.setText(itemData.getConsignee());
			mTel.setText(itemData.getPhone());
			mAddrss.setText(itemData.getAreaName()+itemData.getAddress());

		}

	}

	@Override
	public void onRefresh(int page) {//刷新
		updateAddressList(1, true);

	}

	@Override
	public void onLoadMore(int page) { //加载
		nowPage++;
		updateAddressList(nowPage, false);
	}
	private void updateAddressList(final int pageNum,final boolean isRefresh){

		//		mLoadMoreProxy.loadDataActionComplete(false);

		new Thread(){
			public void run() {
				try{
					WebClient client = WebClient.getInstance(AddressManagerActivity.this);

					PageEntity<MyConsigneeAddress> entry = client.receiver(pageNum, 10, orderProperty, "desc");

					int totlePage = entry.getTotalPages();
					mConsigneeAddresses = entry.getContent();
					if(pageNum > totlePage){
						App.showShortToast(R.string.the_end_page);
						mConsigneeAddresses = null;
					}
				} catch (WebException e) {
					if (e.getStatusCode() == WebException.TYPE_SERVER_RETURN_NULL)
						mConsigneeAddresses = null;
					else
						e.printStackTrace();
				}

				if(isRefresh)
					mHandler.sendEmptyMessage(0);	
				else
					mHandler.sendEmptyMessage(1);
			};
		}.start();

		//		mLoadMoreProxy.loadDataActionComplete(true);

	}
	private class MyHandler extends Handler{
		private WeakReference<Activity> mActivity;

		private MyHandler(Activity activity){
			mActivity = new WeakReference<Activity>(activity);
		}

		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			if( mActivity.get() != null ){
				switch (msg.what) {
				case 0:
					mAdapter.update(mConsigneeAddresses);
					mRefreshListView.onRefreshComplete();
					break;
				case 1:
					mAdapter.append(mConsigneeAddresses);
					mRefreshListView.onRefreshComplete();
					break;
				case 2:
					dismissLoadingDialog();
					onRefresh(1);
					break;

				default:
					break;
				}

			}
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		onRefresh(1);
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent,
			View view, final int position, long id) {

		ShowDeleteDialog(position);

		return true;
	}

	private void ShowDeleteDialog(final int pos) {
		dismissDeleteDialog();
		mAddressDeleteDialog = new DoubleButtonDialog(this);
		mAddressDeleteDialog.showDialog(getString(R.string.info_delet_this_search), new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				showLoadingDialog("");

				new Thread(){
					public void run() {
						try {
							WebClient.getInstance(AddressManagerActivity.this).receiverDelete(mAdapter.getData().get(pos).getId()+"");
							mHandler.sendEmptyMessage(2);
						} catch (WebException e) {
							dismissLoadingDialog();
							e.printStackTrace();
						}
					};
				}.start();
			}
		});


	}
	@Override
	public void onItemClick(AdapterView<?> parent, View view,
			int position, long id) {
		Intent intent = new Intent(AddressManagerActivity.this,NewAddressActivity.class);
		intent.putExtra("inputType", "modify");
		intent.putExtra("id", mAdapter.getData().get(position).getId()+"");
		intent.putExtra("consignee", mAdapter.getData().get(position).getConsignee());
		intent.putExtra("areaName", mAdapter.getData().get(position).getAreaName());
		intent.putExtra("phone", mAdapter.getData().get(position).getPhone());
		intent.putExtra("address", mAdapter.getData().get(position).getAddress());
		intent.putExtra("marea", mAdapter.getData().get(position).getArea().getId()+"");
		intent.putExtra("zipCode", mAdapter.getData().get(position).getZipCode());
		intent.putExtra("isDefault", mAdapter.getData().get(position).getIsDefault());

		startActivity(intent);


		//		final String mid = mAdapter.getData().get(position).getId()+"";
		//		new Thread(){
		//			public void run() {
		//				try {
		//					WebClient.getInstance(AddressManagerActivity.this).modifyAddress(mid, "aaaa", "bbbb", false, "18885656562", "215000", "3");
		//					mHandler.sendEmptyMessage(2);
		//				} catch (WebException e) {
		//					e.printStackTrace();
		//				}
		//			};
		//		}.start();

	}

	private void dismissDeleteDialog() {

		if( mAddressDeleteDialog != null && mAddressDeleteDialog.isShowing() ) {
			mAddressDeleteDialog.dismiss();
		}
		mAddressDeleteDialog = null;

	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		dismissDeleteDialog();
		mHandler.removeCallbacksAndMessages(null);
	}



}
